//
//  BQOAuthController.swift
//  BQWB
//
//  Created by laibingqiang on 16/10/25.
//  Copyright © 2016年 laibingqiang. All rights reserved.
//

import UIKit
import YYModel
import SVProgressHUD
class BQOAuthController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
    
        setupNav()
    }
    
    override func loadView() {
        view = webV
    }
    
    @objc private func CancelClink(){
        
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc private func AutoClink(){
        
        print("自动填充")
        //js注入
        let jsString = "document.getElementById('userId').value='\(BQNAME)',document.getElementById('passwd').value='\(BQPASSWORD)'"
        
        webV.stringByEvaluatingJavaScript(from: jsString)
    }
    private func setupNav(){
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(target: self, action: #selector(CancelClink), imgName: nil, backImg: nil, title: "取消")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(target: self, action: #selector(AutoClink), imgName: nil, backImg: nil, title: "自动填充")
    }
    

    private lazy var webV:UIWebView = {
        
        let w = UIWebView()
        //设置代理
        w.delegate = self
        
        let url:URL = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=3312518011&redirect_uri=http://www.baidu.com")!
        let request:URLRequest = URLRequest(url: url)
        w.loadRequest(request)
        
        return w
        
    }()
}





//webV的代理方法
extension BQOAuthController:UIWebViewDelegate{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.url?.absoluteString
        
        if let u = urlString,u.hasPrefix(BQREDIRECTURI){
            
            let query = request.url?.query
            
            if let q = query{
                
                let code:String = q.substring(from: "code=".endIndex)
                
                BQOAuthViewModel.shared.getUserAccount(code: code, finish: { (res) in
                    if res == false{
                        
                        SVProgressHUD.dismiss()
                        return
                    }
                    
                    self.dismiss(animated: true, completion: { 
                        
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "通知"), object: nil)
                    })
                    
                })
                
                
                
            }
            
            SVProgressHUD.dismiss()
            return false
            
        }
                //getUserAccount(code: code)
                return true
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show(withStatus: "正在加载")
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
    
}






//网络请求方法

//extension BQOAuthController{
//    
//    func getUserAccount(code:String){
//        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        // 请求参数
//        let params = [
//            "client_id": BQAPPKEY,
//            "client_secret": BQAPPSECRET,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": BQREDIRECTURI
//        ]
//        // 发送请求
//        NetworkTool.shared.request(method: NetworkTool.BQNetworkTollMethod.post, URLString: urlString, parameters: params, success: { (response) in
//            
//            guard let res = response else{
//                
//                return
//            }
//            
//            let model:BQOAuthModel = BQOAuthModel.yy_model(withJSON: res)
//            
//            //print(model)
//            
//            getUserInfo(model: model)
//            
//            }) { (error) in
//                
//                print(error)
//        }
//        
//    }
//}
//
//
//func getUserInfo(model:BQOAuthModel){
//    
//    // 请求 urlString
//    let urlString = "https://api.weibo.com/2/users/show.json"
//    
//    // 请求参数
//    let params = [
//        "access_token":model.access_token!,
//        "uid":model.uid!
//    ]
//    
//    NetworkTool.shared.request(method: NetworkTool.BQNetworkTollMethod.get, URLString: urlString, parameters: params, success: { (response) in
//        
//        guard let res = response as? [String:Any] else{
//            
//            return
//        }
//        
//        model.screen_name = res["screen_name"] as? String
//        
//        model.avatar_large = res["avatar_large"] as? String
//        
//        BQOAuthViewModel.shared.saveUserAccountModel(model: model)
//        
//        }) { (error) in
//            
//            print(error)
//    }
//
//    

//}
